package com.yami.shop.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yami.shop.common.bean.MeltCloudConfig;
import com.yami.shop.common.util.ParamSignUtil;
import com.yami.shop.common.util.StringUtils;
import com.yami.shop.service.SysConfigService;
import io.rong.RongCloud;
import io.rong.util.CodeUtil;
import io.rong.util.CommonUtil;
import io.rong.util.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class ApiUtilServiceImpl {

    @Autowired
    private RongCloud rongCloud;

    @Autowired
    private SysConfigService sysConfigService;

    /**
     * HTTP post请求
     * 默认 application/x-www-form-urlencoded 类型
     * @param uri 接口路径
     * @param map 参数
     * @return
     * @throws Exception
     */
    public JSONObject requestPost(String uri, Map<String, Object> map) throws Exception{
        return this.requestPost(uri, null, map);
    }
    
    /**
     * HTTP post请求
     * @param uri 接口路径
     * @param contentType 类型
     * @param map 参数
     * @return
     * @throws Exception
     */
    public JSONObject requestPost(String uri, String contentType, Map<String, Object> map) throws Exception {
        MeltCloudConfig config = sysConfigService.getSysConfigObject("MELT_CLOUD_CONFIG", MeltCloudConfig.class);
        String random = RandomUtil.randomNumbers(10);
        String timestamp = String.valueOf(DateUtil.current());
        String sign = config.getAppSecret() + random + timestamp;
        String signature = ParamSignUtil.shaEncode(sign);
        log.info("随机数：" + random + " 时间戳：" + timestamp + " 签名串：" + sign + " SHA1：" + signature);
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("App-Key", config.getAppKey());
        headerMap.put("Nonce", random);
        headerMap.put("Timestamp", timestamp);
        headerMap.put("Signature", signature);
        String domain = rongCloud.config.getDomain();
        if (StringUtils.isEmpty(contentType)) {
            contentType = "application/x-www-form-urlencoded";
        }
        String param = "";
        if (contentType.equals("application/x-www-form-urlencoded")) {
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                sb.append("&").append(entry.getKey()).append("=").append(URLEncoder.encode(String.valueOf(entry.getValue()), "UTF-8"));
            }
            param = sb.substring(1);
        } else if (contentType.equals("application/json")) {
            param = JSON.toJSONString(map);
        }
        
        String result = HttpRequest.post(domain + uri).contentType(contentType).addHeaders(headerMap).body(param).setConnectionTimeout(30000).execute().body();
        log.info("接口返回数据：" + result);
        JSONObject jsonObject =  JSON.parseObject(result);
        return jsonObject;
        
    }
    
}
